package cn.xpf.study.utils;

import cn.xpf.study.model.LessonItemContent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.util.ArrayList;
import java.util.List;

/**
 * Create on 2021/5/15
 *
 * @author shuxinsheng@qiyi.com
 **/
public class JsonUtil {

    public static final ObjectMapper mapper = new ObjectMapper();

    public static final JavaType javaType = mapper.getTypeFactory()
            .constructParametricType(ArrayList.class, LessonItemContent.class);

    static {
        // 转换为格式化的json
        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        // 如果json中有新增的字段并且是实体类类中不存在的，不报错
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static List<LessonItemContent> fromContent(String content) {
        try {
            return mapper.readValue(content, javaType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    public static String contentToJson(List<LessonItemContent> contents) {
        try {
            return mapper.writeValueAsString(contents);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
